<template>
  <div class="realtime-price">
    <span :style="{ color: price_color, 'font-size': fontSize }">
      {{ realtimePrice || "--"
      }}<i :style="{ color: price_color }" :class="priceIconClass"
    /></span>
  </div>
</template>

<script>
import { channels } from "@/js/core";
export default {
  name: "RealtimePrice",
  props: {
    newPrice: Number,
    fontSize: {
      type: String,
      default: "0.8rem",
    },
    autoUpdate: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      indexPrice: null,
      unsubkey: null,
      price_color: "",
      priceIconClass: {
        "el-icon-top": false,
        "el-icon-bottom": false,
        "el-icon-minus": false,
        none: true,
      },
    };
  },
  methods: {
    beforeUpdatePrice(newPrice, oldPrice) {
      if (newPrice > oldPrice) {
        this.price_color = "#67C23A";
        this.priceIconClass = { "el-icon-top": true };
      } else if (newPrice < oldPrice) {
        this.price_color = "#F56C6C";
        this.priceIconClass = { "el-icon-bottom": true };
      } else {
        this.price_color = "#303133";
        this.priceIconClass = { "el-icon-minus": true };
      }
      this.indexPrice = newPrice;
    },
  },
  computed: {
    realtimePrice() {
      if (!this.autoUpdate) {
        this.beforeUpdatePrice(this.newPrice, this.indexPrice);
      }

      return this.indexPrice;
    },
  },
  mounted() {
    if (this.autoUpdate) {
      this.unsubkey = channels.BTC_INFO.sub((news, old) =>
        this.beforeUpdatePrice(news.indexPrice, old.indexPrice)
      );
    }
  },
  beforeDestroy() {
    if (this.autoUpdate) {
      channels.BTC_INFO.unsub(this.unsubkey);
    }
  },
};
</script>

<style></style>
